package com.game.center.service;


import com.game.center.entity.User;
import com.game.center.mapper.UserMapper;
import com.game.center.respository.UserRespository;
import com.game.common.error.IServerError;
import com.game.netty.http.request.LoginParam;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

/**
 * @Author 林道敬
 * @Date 2023-07-29
 * @Description
 **/
@Service
public class UserLoginService {

    @Autowired
    private UserRespository userRespository;
    @Autowired
    private UserMapper userMapper;

    public IServerError verfiyLoginParam(LoginParam loginParam) {

        return null;
    }

    public IServerError verfiySdkToken(String openId, String token) {
        // 这里调用sdk服务端验证接口

        return null;
    }

    public User login(LoginParam loginParam) {

        String openId = loginParam.getOpenid();
        openId = openId.intern();//放openId放入到常量池
        synchronized (openId) {// 对openId加锁，防止用户点击多次注册多次
            Optional<User> op = userRespository.findById(openId);
            User user = null;
            if (!op.isPresent()) {
                // 用户不存在，自动注册
                user = this.register(loginParam);
            } else {
                user = op.get();
            }
            return user;
        }
    }

    private User register(LoginParam loginParam) {

//        long userId = userRespository.getNextUserID();// 使用redis自增保证userId全局唯一
        User user = new User();
        user.setUserName("lindaojng");
        user.setEmail("857070484");
        user.setPassword("123456");
        user.setId(loginParam.getOpenid());
        user.setOpenid(loginParam.getOpenid());
        userMapper.insert(user);
        return user;

    }

    public Optional<User> getUserByOpenId(String openId) {
        return userRespository.findById(openId);
    }

}
